package run.siyuan.jdk.漫画算法.队列;

/**
 * @ClassName QueueTest
 * @Description TODO 利用数组实现队列,队列先进先出
 * @Author siyuan
 * @Date 2023/4/8 09:53
 */
public class ArrayQueue {

    private int[] array;
    private int headIndex;
    private int lastIndex;

    private int size = 0;

    public ArrayQueue(int capacity) {
        this.array = new int[capacity];
        headIndex = 0;
        lastIndex = 0;
    }

    public static void main(String[] args) {
        ArrayQueue queue = new ArrayQueue(4);
        queue.enqueue(10);
        queue.enqueue(11);
        queue.enqueue(12);
        queue.dequeue();
        queue.dequeue();
        queue.dequeue();
        queue.enqueue(13);
        queue.enqueue(14);
        queue.enqueue(15);
        queue.show();

    }

    /**
     * 入队列
     *
     * @param element
     */
    public void enqueue(int element) {
        if (size == array.length - 1){
            throw new RuntimeException("队列已满");
        }
        if (headIndex == lastIndex && size == array.length - 2) {
            throw new RuntimeException("队列已满");
        }
        this.array[lastIndex] = element;
        lastIndex++;
        lastIndex = lastIndex % this.array.length;
        size++;
    }

    /**
     * 出队列
     */
    public void dequeue() {
        if (size == 0 && headIndex == lastIndex) {
            throw new RuntimeException("队列为空");
        }
        int element = this.array[headIndex];
        this.array[headIndex] = 0;
        headIndex++;
        headIndex = headIndex % this.array.length;
        size--;
    }

    /**
     * 打印
     */
    public void show() {
        for (int i = 0; i < this.array.length; i++) {
            System.out.printf("%d\t%d\n", i, this.array[i]);

        }
    }


}
